<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .success {color: green; }
        .error {color: red}
        .form-control {margin: 10px 0;}
    </style>
</head>

<body>
    <form id="reg-form">
        <div class="form-control">
            <input id="user" type="text" placeholder="请输入用户名">
            <!-- 提示内容 -->
            <span></span>
        </div>
        <div class="form-control">
            <button>立即注册</button>
        </div>
    </form>
    <script>
        // 已经被注册过的账号(用户名)
        var accounts = ['jack', 'rose', 'tom', 'robin', 'charles', 'frank']
        var user = document.querySelector('#user')
        var regForm = document.querySelector('#reg-form')
        // 用来记录错误
        var error
        user.oninput = function () {
            // 获取用户输入内容
            if (accounts.includes(this.value)) {  // 账号被占用
                user.nextElementSibling.className = 'error'
                user.nextElementSibling.innerHTML = '用户名已经被占用, 请重新换一个'
                error = '用户名被占用'
            } else {
                // 账号可用
                user.nextElementSibling.className = 'success'
                user.nextElementSibling.innerHTML = '恭喜您, 用户名可用'
                error = null
            }
        }
        regForm.onsubmit = function (e) {
            // 阻止事件默认行为
            e.preventDefault()
            if (error) {
                alert(error) 
                return
            }
            alert('账号注册中...')
            // 后续代码
        }
    </script>
</body>

</html>